//
//  CLGWebViewController.m
//  NativeWebDemo
//
//  Created by GuochengLiu on 2017/2/6.
//  Copyright © 2017年 sumavision. All rights reserved.
//

#import "CLGWebViewController.h"
#import <WebKit/WebKit.h>
#import "UIViewController+CLGExtension.h"
#import "UINavigationController+SGProgress.h"
#import <MJRefreshNormalHeader.h>

@interface CLGWebViewController () <WKNavigationDelegate>

@property (strong, nonatomic) WKWebView *webView;

@end

@implementation CLGWebViewController

- (instancetype)initWithURL:(NSURL *)url title:(NSString *)title
{
    self = [super initWithNibName:@"CLGWebViewController" bundle:nil];
    if (self) {
        self.webURL = url;
        self.webTitle = title;
        self.showProgress = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_webTitle != nil) {
        self.title = _webTitle;
    }
    [self.view addSubview:self.webView];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:self.webURL]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setSGProgressPercentage:-100];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.webView.frame = self.view.frame;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (_showProgress == YES) {
            [self.navigationController setSGProgressPercentage:_webView.estimatedProgress * 100];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        if (_webTitle == nil) {
            self.title = _webView.title;
        }
    }
}

- (WKWebView *)webView
{
    if (_webView == nil) {
        _webView = [[WKWebView alloc] init];
        [_webView setNavigationDelegate:(id<WKNavigationDelegate> _Nullable)self];
        [_webView setUIDelegate:(id<WKUIDelegate> _Nullable)self];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil];
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}

#pragma mark - <WKNavigationDelegate>


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
        
        NSURL *hrefURL = navigationAction.request.URL;
        
        if ([hrefURL.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [hrefURL.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) {
            CLGWebViewController *webVC = [[CLGWebViewController alloc] initWithURL:hrefURL title:nil];
            webVC.showProgress = _showProgress;
            [self.navigationController pushViewController:webVC animated:YES];
        } else {
            
            if ([hrefURL.scheme caseInsensitiveCompare:@"UVideoShandong"] == NSOrderedSame) {
                Class class = NSClassFromString(hrefURL.host);
                
                NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
                
                NSURLComponents *components = [NSURLComponents componentsWithURL:hrefURL resolvingAgainstBaseURL:NO];
                
                NSArray *queryItems = components.queryItems;
                
                for (NSURLQueryItem *queryItem in queryItems) {
                    [paramDict setValue:queryItem.value forKey:queryItem.name];
                }
                
                UIViewController *vc = [[class alloc] initWithParamDict:paramDict];
                
                if (vc == nil) {
                    NSLog(@"%@不存在", hrefURL.host);
                } else {
                    [self.navigationController pushViewController:vc animated:YES];
                }
            } else {
                [[UIApplication sharedApplication] openURL:hrefURL];
            }
        }
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    [self showLoadingSpinner];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    [self dismissLoadingSpinner];

}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
}

#pragma mark - <WKUIDelegate>

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action) {
                                                       completionHandler();
                                                   }];
    [alertController addAction:action];
    [alertController setPreferredAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"title"];
}

@end
